package com.example.jobback.service.seeker.impl;

import com.example.jobback.config.AuthConfig;
import com.example.jobback.mapper.SeekerMapper;
import com.example.jobback.po.Seeker;
import com.example.jobback.po.User;
import com.example.jobback.req.common.password.ResetPasswordReq;
import com.example.jobback.req.common.phone.ResetPhoneReq;
import com.example.jobback.result.Result;
import com.example.jobback.service.common.UserCommonService;
import com.example.jobback.service.seeker.SeekerAuthService;
import com.example.jobback.util.CACHEUtil;
import com.example.jobback.util.SecureEncryptionUtil;
import com.example.jobback.util.TLUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

import static com.example.jobback.util.RedisConstants.SEEKER_KEY;
import static com.example.jobback.util.RedisConstants.SEEKER_TTL;
import static java.time.LocalDateTime.now;

/**
 * @ClassName: SeekerAuthServiceImpl
 * @Description:求职者-身份核验实现类
 * @Author: lhb
 * @Date: 2025/6/21
 */
@Service
public class SeekerAuthServiceImpl implements SeekerAuthService {


    private final UserCommonService userCommonService;

    private final AuthConfig authConfig;

    private final CACHEUtil cacheUtil;

    private final SeekerMapper seekerMapper;

    public SeekerAuthServiceImpl(UserCommonService userCommonService, AuthConfig authConfig, SeekerMapper seekerMapper, CACHEUtil cacheUtil) {
        this.userCommonService = userCommonService;
        this.authConfig = authConfig;
        this.seekerMapper = seekerMapper;
        this.cacheUtil = cacheUtil;
    }

    /**
     * @Description: 登录
     * @param phone
     * @param code
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/6/21 14:38
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> LoginByPhone(String phone, String code) {
        //验证码验证
        String phoneAes=null;
        try {
            if(!userCommonService.verifyCode(phone,code)) throw new IllegalArgumentException("VALIDATION_ERROR:验证码错误");
            phoneAes= SecureEncryptionUtil.encrypt(phone,authConfig.getPhoneSecret());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //查找该电话号码的三端记录
        User user=userCommonService.getUserByPhoneAes(phoneAes);
        if(user==null){
            //用户三端都未注册过
            user= userCommonService.registerUser(phoneAes);
        }
        Long userId = user.getUserId();
        Seeker seeker=seekerMapper.getSeekerByUserId(userId);
        if(seeker == null) {
            //求职端未注册
            seeker=new Seeker();
            BeanUtils.copyProperties(user, seeker);
            seeker.setCreatedAt(now());
            seeker.setUpdatedAt(now());
            // 使用BeanUtils.copyProperties将User的字段复制到Seeker
            if(seekerMapper.register(seeker)==0) throw new RuntimeException("注册失败");
        }else {
            BeanUtils.copyProperties(user, seeker);
        }
        //删除三端登录记录，只允许一端登录
        userCommonService.deleteAllLoginKeys(userId);
        //获取token，写入redis
        String token = userCommonService.setRedisUser(seeker,seeker.getUserId(),SEEKER_KEY,authConfig.getJwtSeekerSecret(),SEEKER_TTL, TimeUnit.DAYS);
        if(token==null) throw new RuntimeException("token生成失败");
        return Result.success(token);
    }

    /**
     * @Description: 退出登录
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/6/21 14:42
     */
    @Override
    public Result<Object> LoginOut() {
        Long userId= TLUtil.get(TLUtil.S).getUserId();
        String key=SEEKER_KEY+userId.toString();
        if (cacheUtil.deleteIfExists(key))return Result.success();
        throw new RuntimeException("退出登录失败");
    }

    /**
     * @Description: 新求职者登录
     * @param phone
     * @param password
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/6/23 14:23
     */
    @Override
    public Result<Object> login(String phone, String password) {
        String phoneAes= null;
        String passwordAes=null;
        //加密电话号码和密码
        try {
            phoneAes = SecureEncryptionUtil.encrypt(phone,authConfig.getPhoneSecret());
            passwordAes = SecureEncryptionUtil.encrypt(password,authConfig.getPasswordSecret());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //查看用户记录
        User user=userCommonService.getUserByPhoneAes(phoneAes);
        if(user==null) throw new NullPointerException("无用户记录");
        Long userId = user.getUserId();
        //核验密码
        if(!userCommonService.authUserPassword(userId,passwordAes)){
            throw new IllegalArgumentException("VALIDATION_ERROR:用户名或者密码错误");
        }
        //如果其他端注册过，这一端不用再注册
        Seeker seeker=seekerMapper.getSeekerByUserId(userId);
        if(seeker == null) {
            //求职端未注册
            seeker=new Seeker();
            BeanUtils.copyProperties(user, seeker);
            seeker.setCreatedAt(now());
            seeker.setUpdatedAt(now());
            // 使用BeanUtils.copyProperties将User的字段复制到Seeker
            if(seekerMapper.register(seeker)==0) throw new RuntimeException("登录失败");
        }else {
            BeanUtils.copyProperties(user, seeker);
        }
        //删除三端登录记录，只允许一端登录
        userCommonService.deleteAllLoginKeys(userId);
        //获取token，写入redis
        String token = userCommonService.setRedisUser(seeker,seeker.getUserId(),SEEKER_KEY,authConfig.getJwtSeekerSecret(),SEEKER_TTL, TimeUnit.DAYS);
        if(token==null) throw new RuntimeException("token生成失败");
        return Result.success(token);
    }

    /**
     * @Description: 新用户注册
     * @param phone
     * @param password 
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/6/23 14:35
     */
    @Override
    public Result<Object> register(String phone, String password) {
        String phoneAes= null;
        String passwordAes=null;
        //加密电话号码和密码
        try {
            phoneAes = SecureEncryptionUtil.encrypt(phone,authConfig.getPhoneSecret());
            passwordAes = SecureEncryptionUtil.encrypt(password,authConfig.getPasswordSecret());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //查看用户记录
        if(userCommonService.getUserByPhoneAes(phoneAes)!=null) {
            throw new IllegalArgumentException("VALIDATION_ERROR:该电话号码已被注册");
        }
        User user= userCommonService.registerUser(phoneAes);
        Long userId=user.getUserId();
        if(userCommonService.registerUserAuth(userId,passwordAes)==0) {
            throw new RuntimeException("注册失败");
        }
        //注册求职端
        Seeker seeker=new Seeker();
        BeanUtils.copyProperties(user, seeker);
        seeker.setCreatedAt(now());
        seeker.setUpdatedAt(now());
        // 使用BeanUtils.copyProperties将User的字段复制到Seeker
        if(seekerMapper.register(seeker)==0) throw new RuntimeException("注册失败");
        return Result.success("注册成功");
    }

    /**
     * @Description: 修改密码
     * @param resetPasswordReq
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/7/25 17:25
     */
    @Override
    public Result<Object> resetPassword(ResetPasswordReq resetPasswordReq) {
        Seeker seeker = TLUtil.get(TLUtil.S);
        Long userId = seeker.getUserId();
        String phoneAes = seeker.getPhoneAes();
        return userCommonService.resetPassword(resetPasswordReq, phoneAes, userId);
    }

    /**
     * @Description: 更换手机号
     * @param resetPhoneReq
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/7/26 14:04
     */
    @Override
    public Result<Object> resetPhone(ResetPhoneReq resetPhoneReq) {
        Seeker seeker = TLUtil.get(TLUtil.S);
        Long userId = seeker.getUserId();
        String phoneAes = seeker.getPhoneAes();
        return userCommonService.resetPhone(resetPhoneReq, phoneAes, userId);
    }
}
